package com.leetcodehot.problems;

public class problems92 {
    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode reverseBetween(ListNode head, int left, int right) {
        //哨兵节点
        ListNode dummy = new ListNode(0, head);
        ListNode p0 = dummy;
        int count = 1;
        while (count < left) {
            p0 = p0.next;
            count++;
        }
        //需要pre=null。断链
        ListNode pre = null;
        ListNode cur = p0.next;
        while (count < right + 1) {
            ListNode nxt = cur.next;
            cur.next = pre;
            pre = cur;
            cur = nxt;
            count++;
        }

        //不能换顺序
        p0.next.next = cur;
        p0.next = pre;

        return dummy.next;
    }
}
